<script lang="tsx" setup>
import { CirclePlus, Delete, EditPen } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getMessageListApi } from './http/manage_mes'
import MessageDrawer from './modules/MessageDrawer.vue'
import type { ColumnProps, ProTableInstance } from '@/components/ProTable/interface'
import { ref,reactive } from 'vue'
defineOptions({
  name: 'MessageList',
})

const proTableRef = ref<ProTableInstance>()

// 表格初始查询参数
const initTableParam = reactive({})

// 表格数据回调
function dataCallback(data: any) {
  return {
    list: (data && data.records) || [],
    total: (data && data.total) || 0,
  }
}

// 获取表格数据（模拟接口）
async function getTableList(params: any) {
  // 这里替换为你自己的 API 请求
  // return await getMessageListApi(params)
  let newParams = { ...params }
  console.log('请求消息列表:', params)
  return getMessageListApi(newParams)
}

// 表格列配置
const columns = reactive<ColumnProps[]>(
  [
    {
      type: 'index',
      label: '序号',
      width: 80,
    },
    {
      prop: 'title',
      label: '标题',
      minWidth: 120,
      search: { el: 'input' },
    },
    {
      prop: 'sender',
      label: '发送人',
      minWidth: 100,
      search: { el: 'input' },
    },
    {
      prop: 'status',
      label: '状态',
      enum: [
        { label: '已阅', value: 'ENABLED' },
        { label: '未读', value: 'DISABLED' },
      ],
      fieldNames: { label: 'label', value: 'value' },
      minWidth: 100,
      search: { el: 'tree-select', props: { filterable: true } },
      render: (scope: { row: any }) => {
        return (
          <el-tag type={scope.row.status === 'ENABLED' ? 'success' : 'danger'}>
            {scope.row.status === 'ENABLED' ? '已阅' : '未读'}
          </el-tag>
        )
      },
    },
    {
      prop: 'createTime',
      label: '发送时间',
      minWidth: 160,
      search: {
        el: 'date-picker',
        span: 1,
        props: { type: 'datetimerange', valueFormat: 'YYYY-MM-DD HH:mm:ss' },
      },
    },
    {
      prop: 'operation',
      label: '操作',
      fixed: 'right',
      width: 200,
    },
  ],
)

const drawerRef = ref()
function handelOpenDrawer(type: string, row?: any) {
  const params = {
    title: type === 'add' ? '新增' : type === 'edit' ? '编辑' : '查看',
    isView: type === 'show',
    row: { ...row },
    api: type === 'add' ? addMessageApi : type === 'edit' ? editMessageApi : undefined,
    getTableList: proTableRef.value?.getTableList,
  }
  console.log('params', params)
  drawerRef.value?.acceptParams(params)
}

// 模拟新增接口
async function addMessageApi(params: any) {
  console.log('新增消息:', params)
  return Promise.resolve()
}

// 模拟编辑接口
async function editMessageApi(params: any) {
  console.log('编辑消息:', params)
  return Promise.resolve()
}

// 模拟删除接口
async function delMessageApi(params: any) {
  console.log('删除消息:', params)
  return Promise.resolve()
}

function handleDelMessage(row: any) {
  ElMessageBox.confirm(
    `确定要删除消息【${row.title}】吗？此操作不可恢复！`,
    '提示',
    {
      confirmButtonText: '确认删除',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then(() => {
    // 用户点击确认后执行删除
    delMessageApi({ id: row.id }).then(() => {
      ElMessage.success(`删除【${row.title}】成功`)
      proTableRef.value?.getTableList()
    })
  }).catch(() => {
    // 用户点击取消或关闭弹窗
    ElMessage.info('已取消删除')
  })
}
</script>

<template>
  <div class="table-container">
    <div class="table-box">
      <ProTable
        ref="proTableRef"
        height="100%"
        highlight-current-row
        :border="false"
        title="消息列表"
        :request-api="getTableList"
        :columns="columns"
        :data-callback="dataCallback"
        :init-param="initTableParam"
      >
        <!-- 表格 header 按钮 -->
        <template #tableHeader>
          <div class="flex">
            <el-button type="primary" :icon="CirclePlus" @click="handelOpenDrawer('add')">
              新增消息
            </el-button>
          </div>
        </template>
        <!-- 表格操作 -->
        <template #operation="scope">
          <div class="flex flex-wrap justify-center">
            <el-button type="primary" link :icon="EditPen" @click="handelOpenDrawer('edit', scope.row)">
              编辑
            </el-button>
            <el-button type="danger" link :icon="Delete" @click="handleDelMessage(scope.row)">
              删除
            </el-button>
          </div>
        </template>
      </ProTable>
      <MessageDrawer ref="drawerRef" />
    </div>
  </div>
</template>
